import { RouteRecordRaw } from "vue-router";

import { MenuWrapper, Menu } from "@/service/login/types";

// 菜单树构建
export function buildMenuTree(menus: MenuWrapper[]) {
  const menuMap: { [key: number]: any } = {};
  const tree: any[] = [];

  menus.forEach((item) => {
    const menu = item.menu;
    menu.children = [];
    menuMap[menu.id] = menu;
    if (menu.parentId === null) {
      tree.push(menu);
    } else {
      if (menuMap[menu.parentId]) {
        menuMap[menu.parentId].children.push(menu);
      }
    }
  });

  return tree;
}

// 将菜单树映射为路由
export function mapTreeToRoute(menuTree: Menu[]): RouteRecordRaw[] {
  const modules = import.meta.glob("../views/**/*.vue");
  const routes: RouteRecordRaw[] = [];

  menuTree.forEach((menu) => {
    const filePath = modules[/* @vite-ignore */ `../views${menu.path}.vue`];

    const route: RouteRecordRaw = {
      path: menu.path,
      name: menu.name,
      component: filePath,
      children: menu.children.length > 0 ? mapTreeToRoute(menu.children) : [],
    };
    routes.push(route);
  });

  return routes;
}
// 格式化树形数据
export function formatTreeData(data: MenuWrapper[]) {
  const map = new Map<number, any>();
  const result: any[] = [];
  data.forEach((item) => {
    const menu = item.menu;
    const node = {
      value: menu.id.toString(),
      label: menu.name,
      children: [],
    };
    map.set(menu.id, node);
    if (menu.parentId !== null) {
      const parent = map.get(menu.parentId);
      if (parent) {
        parent.children.push(node);
      }
    } else {
      result.push(node);
    }
  });
  return result;
}
